package com.logreview.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
    private static long pointer=0;
    private static long fileSize=0;

    /**
     * 读取一行文件
     * @param path
     */
    public static synchronized String readline(String path) throws Exception {
        File file = new File(path);
        if(file==null || !file.exists()){
            logger.error("file not found {}",path);
            return "";
        }

//        Thread.sleep(1);//线程切换，如果不切换，会导致文件修改保存的瞬间，file.length=0
//        if(file.length() < fileSize){
//            logger.warn("文件重新生成,oldFileSize:{},newFileSize:{},从0开始读取新文件",fileSize,file.length());
//            pointer=0;
//            fileSize=0;
//        }

        RandomAccessFile raf=new RandomAccessFile(file, "r");
        raf.seek(pointer);
        //循环读取
        String line = raf.readLine();
        logger.debug("readline, line={},pointer={},thread={}",line,pointer,Thread.currentThread());
        pointer = raf.getFilePointer();
        fileSize = file.length();
        return  line;
    }


    public static final boolean append(String path, String content)  throws IOException
    {
        FileWriter fw = null;
        try {
            fw = new FileWriter(path,true); //建立FileWriter对象，并实例化fw
            //将字符串写入文件
            fw.write(content);
            fw.close();
        }
        catch (IOException e) {
            throw e;
        }finally{
            if(null != fw){
                fw.close();
            }
        }
        return true;
    }

    /**
     * 判断两个文件的内容是否相同，文件名要用绝对路径
     * @param fileName1 ：文件1的绝对路径
     * @param fileName2 ：文件2的绝对路径
     * @return 相同返回true，不相同返回false
     */
    public static boolean isSameFile(String fileName1,String fileName2){
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;
        try {
            fis1 = new FileInputStream(fileName1);
            fis2 = new FileInputStream(fileName2);

            int len1 = fis1.available();//返回总的字节数
            int len2 = fis2.available();

            if (len1 == len2) {//长度相同，则比较具体内容
                //建立两个字节缓冲区
                byte[] data1 = new byte[len1];
                byte[] data2 = new byte[len2];

                //分别将两个文件的内容读入缓冲区
                fis1.read(data1);
                fis2.read(data2);

                //依次比较文件中的每一个字节
                for (int i=0; i<len1; i++) {
                    //只要有一个字节不同，两个文件就不一样
                    if (data1[i] != data2[i]) {
                        logger.warn("文件对比失败,file1:{},file2:{},原因:{},data1[{}]:{} <> data2[{}]:{}",fileName1,fileName2,"文件内容不一样",i,data1[i],i,data2[i]);
                        return false;
                    }
                }
                //System.out.println("两个文件完全相同");
                return true;
            } else {
                //长度不一样，文件肯定不同
                logger.warn("文件对比失败,file1:{},file2:{},原因:{}",fileName1,fileName2,"字节数不一致");
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭文件流，防止内存泄漏
            if (fis1 != null) {
                try {
                    fis1.close();
                } catch (IOException e) {
                    //忽略
                    e.printStackTrace();
                }
            }
            if (fis2 != null) {
                try {
                    fis2.close();
                } catch (IOException e) {
                    //忽略
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public static long getPointer() {
        return pointer;
    }

    public static void setPointer(long pointer) {
        FileUtil.pointer = pointer;
    }

    public static void main(String[] args) throws Exception {

        Runnable r = new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        FileUtil.readline("D:\\tmp\\log.txt");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };


        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.execute(r);
        executorService.execute(r);
        executorService.execute(r);
        executorService.execute(r);
        executorService.execute(r);

        Thread.sleep(5000000);

    }
}
